import p0 from "../image/1.jpg";
import p1 from "../image/2.jpg";
import p2 from "../image/3.jpg";
import p3 from "../image/4.jpg";
window.onload = function () {
    var imgAll = document.querySelectorAll(".banner img");
    imgAll[0].src=p0;
    imgAll[1].src=p1;
    imgAll[2].src=p2;
    imgAll[3].src=p3;
    imgAll[4].src=p1;
    
    var banner = document.querySelector(".banner");
    var ul = document.querySelector("ul");
    var index = 0;//播放图片下标
    var timmerid;//存储定时器id
    var pos = { x: 0, y: 0 };//记录touchstart时候的触摸坐标
    function play() {
        timmerid = setInterval(function () {
            index++;
            var tx = index * 10;
            ul.style.transition = "all 0.5s linear";
            ul.style.transform = "translateX(-" + tx + "%)";
        }, 2000);
    }
    ul.ontransitionend = function () {//当过渡效果执行完成.
        if (index >= 4) {//当最后一张图片过渡动画执行完成后立马回到第一张图并显示.
            index = 0;
            ul.style.transition = "none";//去掉过渡动画.
            ul.style.transform = "translateX(0px)";
        }
    }
    play();
    //给banner绑定 touch事件.
    banner.ontouchstart = function (e) {
        clearInterval(timmerid);
        pos.x = e.touches[0].clientX;
        pos.y = e.touches[0].clientY;
    }
    banner.ontouchmove = function (e) {
        var t = e.touches[0];
        if (index == 0 && (t.clientX - pos.x) > 0) {
            return;
        }
        ul.style.left = (t.clientX - pos.x) + "px";
    }
    banner.ontouchend = function () {
        var left = parseInt(ul.style.left);
        ul.style.left = "0px";
        ul.style.transition = "all 0.5s linear";
        if (left > 30) {//往右拖动距离大于30 应该显示前一张图片
            index--;
        } else if (left < -30) {//往左拖动距离大于30 应该显示下一张图片
            index++;
        }
        var tx = index * 10;
        ul.style.transform = "translateX(-" + tx + "%)";
        play();
    }
}

